<template>
  <div class="racelist">
    <div class="r-header">
      <div class="r-h-title">
        <i class="iconfont icon-liebiao1"></i>比赛列表
      </div>
    </div>
    <div class="r-search">
      <n-input class="r-s-input" placeholder="搜索比赛" round size="small" v-model:value="searchVal">
        <template #suffix>
          <i class="iconfont icon-sousuo" @click="searchParams.name = searchVal"></i>
        </template>
      </n-input>
      <n-button class="r-s-btn" size="small" round type="success" @click="hanlderToCreate"><i
          class="iconfont icon-tianjia"></i>创建</n-button>
    </div>
    <div class="r-table">
      <el-table class="table" :data="raceList.records" size="small" stripe>
        <el-table-column type="index" label="序号" width="100%" align="center" :index="indexMethod" />
        <el-table-column prop="id" label="比赛ID" align="center"></el-table-column>
        <el-table-column prop="title" label="比赛标题" align="center"></el-table-column>
        <el-table-column prop="type" label="比赛类型" align="center">
          <template #default="scoped">
            <n-button class="btn" size="tiny" round type="success" v-show="scoped.row.type == 1">
              <i class="iconfont icon-tuandui"></i>团队赛
            </n-button>
            <n-button class="btn" size="tiny" round type="error" v-show="scoped.row.type == 0">
              <i class="iconfont icon-zuozhe"></i>个人赛
            </n-button>
          </template>
        </el-table-column>
        <el-table-column prop="format" label="赛制" align="center">
          <template #default="scoped">
            <n-button class="btn" size="tiny" round type="warning" ghost>
              <i class="iconfont icon-bisai"></i>
              <span class="text" v-show="scoped.row.format == 0">ACM</span>
              <span class="text" v-show="scoped.row.format == 1">OI</span>
              <span class="text" v-show="scoped.row.format == 2">IOI</span>
              <span class="text" v-show="scoped.row.format == 3">天梯</span>
            </n-button>
          </template>
        </el-table-column>
        <el-table-column prop="auth" label="比赛权限" align="center">
          <template #default="scoped">
            <n-button class="btn" size="tiny" round type="success" strong secondary v-show="scoped.row.auth == 0">
              <i class="iconfont icon-bisai1"></i>
              <span class="text2">公开赛</span>
            </n-button>
            <n-button class="btn" size="tiny" round type="error" strong secondary v-show="scoped.row.auth == 1">
              <i class="iconfont icon-bisai1"></i>
              <span class="text2">私有赛</span>
            </n-button>
            <n-button class="btn" size="tiny" round type="warning" strong secondary v-show="scoped.row.auth == 2">
              <i class="iconfont icon-bisai1"></i>
              <span class="text2">保护赛</span>
            </n-button>
          </template>
        </el-table-column>
        <el-table-column label="是否可见" align="center">
          <template #default="scoped">
            <el-tooltip content="是否展示该比赛" placement="top">
              <el-switch v-model="scoped.row.visible" :active-value="0" :inactive-value="1"
                @change="updateRaceVisible(scoped.row.id, scoped.row.visible)" />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div class="btns">
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button class="btn" size="tiny" type="info" @click="handlerToEdit(scoped.row.id)">
                    <i class="iconfont icon-bianji2"></i>
                  </n-button>
                </template>
                编辑
              </n-tooltip>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button class="btn" size="tiny" type="success"
                    @click="handlerToProblem(scoped.row.id, scoped.row.format)">
                    <i class="iconfont icon-tongzhi"></i>
                  </n-button>
                </template>
                比赛题目
              </n-tooltip>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button @click="handlerToNotice(scoped.row.id)" class="btn" size="tiny" color="rgb(144,147,153)">
                    <i class="iconfont icon-gonggao"></i>
                  </n-button>
                </template>
                比赛公告
              </n-tooltip>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button class="btn" size="tiny" color="#8a2be2" :disabled="scoped.row.type != 1"
                    @click="handlerToGroupList(scoped.row)">
                    <i class="iconfont icon-tuanduishezhi"></i>
                  </n-button>
                </template>
                显示团队信息
              </n-tooltip>

              <n-popconfirm positive-text="确认" negative-text="取消" @positive-click="delRace(scoped.row.id)">
                <template #trigger>
                  <n-tooltip trigger="hover">
                    <template #trigger>
                      <n-button class="btn" size="tiny" type="error">
                        <i class="iconfont icon-shanchu"></i>
                      </n-button>
                    </template>
                    删除
                  </n-tooltip>
                </template>
                确认删除比赛？
              </n-popconfirm>

              <el-popover class="popover" placement="left" :width="150" trigger="hover">
                <template #reference>
                  <n-button class="btn" size="tiny" type="warning">
                    <i class="iconfont icon-qita"></i>
                  </n-button>
                </template>
                <div style="display: flex; justify-content: center">
                  <div class="popover-btns">
                    <el-tooltip content="下载代码" placement="top">
                      <n-button class="btn" :style="{ width: '40px' }" color="rgb(95,219,211)" size="tiny">
                        <i class="iconfont icon-xiazai1"></i>
                      </n-button>
                    </el-tooltip>
                    &emsp13;
                    <el-tooltip content="报名名单" placement="top">
                      <n-button class="btn" :style="{ width: '40px' }" color="rgb(244,104,103)" size="tiny" @click="
                        (isShowUsers = true),
                        (userParams.cid = scoped.row.id),
                        (searchParams2.cid = scoped.row.id)
                        ">
                        <i class="iconfont icon-yonghu"></i>
                      </n-button>
                    </el-tooltip>
                  </div>
                  <!-- &emsp13; -->
                  <!-- <el-tooltip content="其他" placement="top">
                    <n-button class="btn" :style="{ 'width': '40px' }" color="rgb(240,153,152)" size="tiny">
                      <i class="iconfont icon-xiazai1"></i>
                    </n-button>
                  </el-tooltip> -->
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="r-footer">
      <el-pagination class="pagination" :page-sizes="[50, 100]" background small layout="prev, pager, next,sizes"
        :total="Number(raceList.total)" v-model:current-page="searchParams.pageNum"
        v-model:page-size="searchParams.pageSize" />
    </div>
    <el-drawer v-model="isShowUsers" :show-close="false" direction="rtl" class="drawer" :size="drawerSize">
      <template #header="{ close, titleId, titleClass }">
        <h1 :id="titleId" :class="titleClass">
          已报名用户列表
          <n-button style="marginleft: 10px" size="tiny" type="success" round @click="
            (isShowMoreUsers = true), (drawerSize = '100%'), getUserInfoList()
            ">
            <i class="iconfont icon-tianjia"></i>
            添加用户
          </n-button>
        </h1>
        <n-button size="small" round strong secondary type="error" @click="close">
          <i class="iconfont icon-chahao1"></i>
        </n-button>
      </template>
      <el-table class="table" :data="raceUsers.records">
        <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="number" label="学号" align="center">
          <template #default="scoped">{{ scoped.row.number || "--" }}</template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" align="center">
          <template #default="scoped">{{
            scoped.row.realName || "--"
          }}</template>
        </el-table-column>
        <el-table-column label="院校" align="center">
          <template #default="scoped">
            <div class="desc">{{
              (scoped.row.school || "") +
              "-" +
              (scoped.row.college || "") +
              "-" +
              (scoped.row.major || "")
            }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div class="btns">
              <el-tooltip content="踢出比赛" placement="top">
                <n-button class="btn" size="tiny" type="error" @click="removeFromRace(scoped.row.cid, scoped.row.uid)">
                  <i class="iconfont icon-shanchu"></i>
                </n-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <el-pagination class="pagination" :page-sizes="[50, 99]" background small layout="prev, pager, next,sizes"
          :total="Number(raceUsers.total)" v-model:current-page="userParams.pageNum"
          v-model:page-size="userParams.pageSize" />
      </div>
    </el-drawer>
    <el-drawer v-model="isShowMoreUsers" :show-close="false" direction="rtl" class="drawer" @close="drawerSize = '50%'"
      size="50%">
      <template #header="{ close, titleId, titleClass }">
        <div :id="titleId" :class="titleClass">
          <h3>全部用户列表</h3>
          <div class="h1">
            <n-input class="r-s-input" placeholder="搜索用户" round size="tiny" v-model:value="searchVal_name">
              <template #suffix>
                <i class="iconfont icon-sousuo" @click="searchParams2.name = searchVal_name"></i>
              </template>
            </n-input>
            <n-input class="r-s-input" placeholder="搜索班级" round size="tiny" v-model:value="searchVal_major">
              <template #suffix>
                <i class="iconfont icon-sousuo" @click="searchParams2.major = searchVal_major"></i>
              </template>
            </n-input>
            <el-select class="popselect" v-model="searchParams2.majorLike" size="small">
              <el-option label="模糊查询" :value="0" />
              <el-option label="精准查询" :value="1" />
            </el-select>
            <transition>
              <n-button v-show="newSelection.length > 0" class="btn" size="tiny" round type="success"
                style="margin:auto 10px auto auto" @click="appendMore">批量添加</n-button>
            </transition>
          </div>
        </div>
        <n-button size="small" round strong secondary type="error" @click="close">
          <i class="iconfont icon-chahao1"></i>
        </n-button>
      </template>
      <el-table class="table" :data="userList.records" @selection-change="changeSelectedUser">
        <el-table-column type="selection" align="center" />
        <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod2"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="number" label="学号" align="center">
          <template #default="scoped">{{ scoped.row.number || "--" }}</template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" align="center">
          <template #default="scoped">{{
            scoped.row.realName || "--"
          }}</template>
        </el-table-column>
        <el-table-column label="院校" align="center">
          <template #default="scoped">
            <div class="desc">{{
              (scoped.row.school || "") +
              "-" +
              (scoped.row.college || "") +
              "-" +
              (scoped.row.major || "")
            }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div class="btns">
              <el-tooltip content="添加用户" placement="top">
                <n-button class="btn" size="tiny" type="success" @click="appendUserIntoTeam(scoped.row.id)">
                  <i class="iconfont icon-tijiao1"></i>
                </n-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <el-pagination class="pagination" :page-sizes="[50, 99]" background small layout="prev, pager, next,sizes"
          :total="Number(userList.total)" v-model:current-page="searchParams2.pageNum"
          v-model:page-size="searchParams2.pageSize" />
      </div>
    </el-drawer>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref, watch } from "vue"
import { useRoute, useRouter } from "vue-router"
import {
  getRaceListAPI,
  delRaceAPI,
  getRaceUsersAPI,
  removeFromRaceAPI,
  getRaceUsersNoIncludeLeaderAPI,
  appendUserIntoTeamAPI,
  updateRaceVisibleAPI,
} from "@/api/adminAPI/adminAPI"
import { debounce } from "@/utils/global.js"
import { ElMessage } from "element-plus"

const router = useRouter()
const route = useRoute()
const raceList = reactive({
  records: [],
  total: 20,
})

const searchParams = reactive({
  pageNum: 1,
  pageSize: 50,
  format: -1,
  name: "",
})

watch(searchParams, () => {
  getRaceList()
})

onMounted(() => {
  getRaceList()
})

const hanlderToCreate = () => {
  router.push({
    path: "/admin/race/create",
  })
}
const majorOptions = [
  {
    label: '模糊查询',
    value: 0
  },
  {
    label: '精准查询',
    value: 1
  }
]

const indexMethod = (index) => {
  return (searchParams.pageNum - 1) * searchParams.pageSize + index + 1
}

const indexMethod2 = (index) => {
  return (searchParams2.pageNum - 1) * searchParams2.pageSize + index + 1
}

const getRaceList = debounce(() => {
  getRaceListAPI(searchParams)
    .then((res) => {
      if (res.data.code === 200) {
        Object.assign(raceList, res.data.data)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 200)

const searchVal = ref("")
watch(searchVal, (newV) => {
  if (newV.length == 0) {
    searchParams.name = newV
  }
})
const delRace = debounce((id) => {
  delRaceAPI([id])
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg)
        getRaceList()
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 200)

const handlerToEdit = (cid) => {
  router.push({
    path: `list/${cid}/edit`,
  })
}

const handlerToGroupList = (row) => {
  router.push({
    path: `list/${row.id}/grouplist/${row.groupUserMaxCount}`,
  })
}

const handlerToProblem = (cid, format) => {
  router.push({
    path: `list/${cid}/problems/${format}`,
  })
}

const handlerToNotice = (cid) => {
  router.push({
    path: `list/${cid}/notice`,
  })
}

const isShowUsers = ref(false)
const isShowMoreUsers = ref(false)
//获取注册/未注册的用户
const userParams = reactive({
  pageNum: 1,
  pageSize: 50,
  cid: "",
})
watch(userParams, () => {
  getRaceUsers()
})
const raceUsers = ref({
  records: [],
  total: 20,
})
const getRaceUsers = debounce(async () => {
  await getRaceUsersAPI(userParams)
    .then((res) => {
      if (res.data.code === 200) {
        raceUsers.value = res.data.data
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 100)

//移出比赛
const removeFromRace = debounce(async (cid, uid) => {
  await removeFromRaceAPI(cid, [uid])
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg)
        getRaceUsers()
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 100)

const drawerSize = ref("50%")

const searchVal_name = ref("")
watch(() => searchVal_name.value, (newV) => {
  if (newV.length == 0) {
    searchParams2.name = searchVal_name.value
  }
})
const searchVal_major = ref('')
watch(() => searchVal_major.value, (newV) => {
  if (newV.length == 0) {
    searchParams2.major = searchVal_major.value
  }
})
//获取未注册的用户
const searchParams2 = reactive({
  pageNum: 1,
  pageSize: 50,
  cid: "",
  name: "",
  isLeader: 0,
  isReg: 0,
  major: '',
  majorLike: 0
})
watch(searchParams2, () => {
  getUserInfoList()
})
const userList = ref({
  records: [],
  total: 20,
})
const getUserInfoList = debounce(async () => {
  await getRaceUsersNoIncludeLeaderAPI(searchParams2)
    .then((res) => {
      if (res.data.code === 200) {
        if (res.data.data) {
          userList.value = res.data.data
        } else {
          userList.value = {
            records: [],
            total: 0,
          }
        }
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 200)

//添加用户进入已报名列表
const appendUserIntoTeam = debounce(async (uid) => {
  await appendUserIntoTeamAPI(userParams.cid, 0, [uid])
    .then((res) => {
      if (res.data.code === 200) {
        getRaceUsers()
        getUserInfoList()
        ElMessage.success(res.data.msg)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 200)
const appendMore = debounce(async () => {
  await appendUserIntoTeamAPI(userParams.cid, 0, newSelection.value)
    .then((res) => {
      if (res.data.code === 200) {
        newSelection.value.length = 0
        getRaceUsers()
        getUserInfoList()
        ElMessage.success(res.data.msg)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 200)

//更新是否可见
const updateRaceVisible = debounce(async (cid, visible) => {
  await updateRaceVisibleAPI(cid, visible)
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 200)

//选中的用户
const newSelection = ref([])
const changeSelectedUser = (newV) => {
  newSelection.value.length = 0
  newV.forEach(ele => {
    newSelection.value.push(ele.id)
  })
}
</script>
<style lang="less" scoped>
.racelist {
  margin: auto;
  width: 96%;
  height: 92vh;

  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 12px 12px 50px #d9d9d9, -12px -12px 50px #ffffff;
  display: flex;
  flex-direction: column;

  .r-header {
    display: flex;

    .r-h-title {
      height: 30px;
      line-height: 30px;
      font-size: 20px;
      font-weight: 600;
      color: #555;
      display: flex;
      text-align: center;

      .iconfont {
        margin: auto 0;
        font-weight: 700;
        font-size: 28px;
        height: 30px;
      }
    }
  }

  .r-search {
    display: flex;
    height: 30px;
    line-height: 30px;
    margin: 20px 0 0 0;
    padding-bottom: 10px;
    border-bottom: 2px solid @lineColor;

    .r-s-input {
      height: 30px;
      line-height: 30px;
      width: 15%;
    }

    .r-s-btn {
      margin: auto 10px;
    }
  }

  .r-table {
    user-select: none;

    .table {
      height: 72vh;
    }

    .btns {
      display: flex;
      flex-wrap: wrap;
      height: 70px;
      width: 150px;
      justify-content: center;

      .btn {
        margin: auto;
        width: 40px;
        height: 20px;
      }
    }
  }

  .r-footer {
    margin: auto auto 0 auto;
    display: flex;
    justify-content: center;
  }
}

.desc {
  font-size: 10px;
}

.popover {
  .popover-btns {
    display: flex;
  }
}

.drawer {

  .h1 {
    display: flex;
    margin-top: 5px;

    .r-s-input {
      width: 20%;
      margin: auto 10px auto 0;
    }

    .popselect {
      width: 15%;
      margin: auto 10px auto 0;
    }
  }

  .table {
    height: 80vh;
  }

  .footer {
    display: flex;
    justify-content: center;
    margin-top: 5px;
  }
}
</style>
